package com.zlw.framework.core;

import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * @ClassName ClassScanner
 * @Description TODO
 * @Author zhaoluowei
 * @Date 2020/1/28  18:14
 * @Version 1.0
 */


public class ClassScanner {

    public static List<Class<?>> scanClass(String packageName) throws IOException, ClassNotFoundException {
        List<Class<?>> classList = new ArrayList<>();
        classList.clear();
        String path = packageName.replace(".", "/");
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        Enumeration<URL> resource = classLoader.getResources(path);
        while (resource.hasMoreElements()) {
            URL url = resource.nextElement();
            if (url.getProtocol().contains("jar")) {
                JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
                String jarFilePath = jarURLConnection.getJarFile().getName();
                classList.addAll(getClassesFromJar(jarFilePath, path));
            } else {

            }
        }

        return classList;
    }


    private static List<Class<?>> getClassesFromJar(String jarFilePath, String path) throws IOException, ClassNotFoundException {
        List<Class<?>> classList = new ArrayList<>();
        classList.clear();
        JarFile jarFile = new JarFile(jarFilePath);

        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry jarEntry = entries.nextElement();
            String name = jarEntry.getName();
            System.out.println("name : " + name);
            if (name.startsWith(path) && name.endsWith(".class")) {
                String classFullName = name.replace("/", ".").substring(0, name.length() - 6);

                classList.add(Class.forName(classFullName));

            }
        }


        return classList;
    }


}
